#! /usr/bin/env python
"""Generate C code from an ASDL description.
   This file is modified from the original provided in the CPython source.
"""

# TO DO
# handle fields that have a type but no name

import os, sys

import asdl

TABSIZE = 4
MAX_COL = 80

def get_c_type(name):
    """Return a string for the C name of the type.

    This function special cases the default types provided by asdl:
    identifier, string, int.
    """
    # XXX ack!  need to figure out where Id is useful and where string
    if isinstance(name, asdl.Id):
        name = name.value
    if name == 'int': 
        return 'int'
    elif name == 'string' or name == 'identifier': 
        return 'GVMT_OBJECT(str)*'
    elif name in asdl.builtin_types:
        return "GVMT_OBJECT(%s)*" % name
    else:
        return "GVMT_OBJECT(AST_%s)*" % name

def reflow_lines(s, depth):
    """Reflow the line s indented depth tabs.

    Return a sequence of lines where no line extends beyond MAX_COL
    when properly indented.  The first line is properly indented based
    exclusively on depth * TABSIZE.  All following lines -- these are
    the reflowed lines generated by this function -- start at the same
    column as the first character beyond the opening { in the first
    line.
    """
    size = MAX_COL - depth * TABSIZE
    if len(s) < size:
        return [s]

    lines = []
    cur = s
    padding = ""
    while len(cur) > size:
        i = cur.rfind(', ', 0, size)
        if i == -1:
            i = cur.rfind(' ', 0, size)
        else:
            i += 1
        # XXX this should be fixed for real
        if i == -1 and 'GeneratorExp' in cur:
            i = size + 3
        assert i != -1, "Impossible line %d to reflow: %r" % (size, s)
        lines.append(padding + cur[:i])
        if len(lines) == 1:
            # find new size based on brace
            j = cur.find('{', 0, i)
            if j >= 0:
                j += 2 # account for the brace and the space after it
                size -= j
                padding = " " * j
            else:
                j = cur.find('(', 0, i)
                if j >= 0:
                    j += 1 # account for the paren (no space after it)
                    size -= j
                    padding = " " * j
        cur = cur[i+1:]
    else:
        lines.append(padding + cur)
    return lines

def is_simple(sum):
    """Return True if a sum is a simple.

    A sum is simple if its types have no fields, e.g.
    unaryop = Invert | Not | UAdd | USub
    """
    for t in sum.types:
        if t.fields:
            return False
    return True


class EmitVisitor(asdl.VisitorBase):
    """Visit that emits lines"""

    def __init__(self, file):
        self.file = file
        super(EmitVisitor, self).__init__()

    def emit(self, s, depth, reflow=True):
        # XXX reflow long lines?
        if reflow:
            lines = reflow_lines(s, depth)
        else:
            lines = [s]
        for line in lines:
            line = (" " * TABSIZE * depth) + line + "\n"
            self.file.write(line)


class TypeDefVisitor(EmitVisitor):
    def visitModule(self, mod):
        self._emit_type('Visitor', 0)
        for dfn in mod.dfns:
            self.visit(dfn)

    def visitType(self, type, depth=0):
        self.visit(type.value, type.name, depth)

    def visitSum(self, sum, name, depth):
        if is_simple(sum):
            self.simple_sum(sum, name, depth)
        else:
            self.sum_with_constructors(sum, name, depth)
            
    def _emit_type(self, name, depth):
        ctype = get_c_type(name)
        s = "typedef GVMT_OBJECT(AST_%(name)s)* R_AST_%(name)s;" % locals()
        self.emit("extern GVMT_OBJECT(type)* type_AST_%(name)s;" % locals(), depth)        
        self.emit(s, depth)
        self.emit("", depth)

    def simple_sum(self, sum, name, depth):
        self._emit_type(name, depth)
        ctype = get_c_type(name)
        for t in sum.types:
            self._emit_type(t.name, depth)
            self.emit("extern %s hotpy_%s_singleton;" % (ctype, t.name), depth)     

    def sum_with_constructors(self, sum, name, depth):
        self._emit_type(name, depth)
        for t in sum.types:
            self._emit_type(t.name, depth)

    def visitProduct(self, product, name, depth):
        self._emit_type(name, depth)


class StructVisitor(EmitVisitor):
    """Visitor to generate typdefs for AST."""

    def visitModule(self, mod):
        for dfn in mod.dfns:
            self.visit(dfn)

    def visitType(self, type, depth=0):
        self.visit(type.value, type.name, depth)

    def visitSum(self, sum, name, depth):
        self.visit_index = 0
        self.sum_with_constructors(sum, name, depth)

    def sum_with_constructors(self, sum, name, depth):
        def emit(s, depth=depth):
            self.emit(s % sys._getframe(1).f_locals, depth)
        header = ["GVMT_OBJECT(type)* ob_type; /* read-only */"]
        header.append("uintptr_t ref_count;")
        header.append("uintptr_t visit_index;")
        emit("GVMT_OBJECT(AST_%(name)s) {")
        for field in sum.attributes:
            # rudimentary attribute handling
            type = str(field.type)
            assert type in asdl.builtin_types, type
            header.append("%s %s;" % (type, field.name))        
        for line in header:
            emit(line, depth+1)
        emit("};")
        emit("")       
        emit("/* Begin subtypes of %(name)s */")       
        for t in sum.types:
            self.visit(t, header, depth)
        emit("/* End subtypes of %(name)s */")       
        emit("")       

    def visitConstructor(self, cons, header, depth):
        self.emit("GVMT_OBJECT(AST_%s) {" % cons.name, depth)
        for line in header:
            self.emit(line, depth + 1)
        for f in cons.fields:
            self.visit(f, depth + 1)
        self.emit("};", depth)
        self.emit("#define  %s_VISIT_INDEX %d" % (str(cons.name).upper(), self.visit_index), depth)
        self.emit("", depth)
        self.visit_index += 1

    def visitField(self, field, depth):
        # XXX need to lookup field.type, because it might be something
        # like a builtin...
        ctype = get_c_type(field.type)
        name = field.name
        if field.seq:
            self.emit("GVMT_OBJECT(list)* %(name)s;" % locals(), depth)
        else:
            self.emit("%(ctype)s %(name)s;" % locals(), depth)

    def visitProduct(self, product, name, depth):
        self.emit("GVMT_OBJECT(AST_%(name)s) {" % locals(), depth)
        self.emit("GVMT_OBJECT(type)* ob_type; /* read-only */", depth+1)
        self.emit("uintptr_t ref_count;", depth+1)
        for f in product.fields:
            self.visit(f, depth + 1)
        self.emit("};", depth)
        self.emit("", depth)


class PrototypeVisitor(EmitVisitor):
    """Generate function prototypes for the .h file"""

    def visitModule(self, mod):
        for dfn in mod.dfns:
            self.visit(dfn)

    def visitType(self, type):
        self.visit(type.value, type.name)

    def visitSum(self, sum, name):
        if is_simple(sum):
            pass # XXX
        else:
            for t in sum.types:
                self.visit(t, name, sum.attributes)

    def get_args(self, fields):
        """Return list of C argument into, one for each field.

        Argument info is 3-tuple of a C type, variable name, and flag
        that is true if type can be NULL.
        """
        args = []
        unnamed = {}
        for f in fields:
            if f.name is None:
                name = f.type
                c = unnamed[name] = unnamed.get(name, 0) + 1
                if c > 1:
                    name = "name%d" % (c - 1)
            else:
                name = f.name
            # XXX should extend get_c_type() to handle this
            if f.seq:
                ctype = "R_list"
            else:
                ctype = get_c_type(f.type)
            args.append((ctype, name, f.opt or f.seq))
        return args

    def visitConstructor(self, cons, type, attrs):
        args = self.get_args(cons.fields)
        attrs = self.get_args(attrs)
        ctype = get_c_type(type)
        self.emit_function(cons.name, ctype, args, attrs)

    def emit_function(self, name, ctype, args, attrs, union=True):
        args = args + attrs
        argstr = ", ".join(["%s %s" % (atype, aname)
                            for atype, aname, opt in args])
        margs = "a0"
        for i in range(1, len(args)+1):
            margs += ", a%d" % i
#        self.emit("#define %s(%s) _Py_%s(%s)" % (name, margs, name, margs), 0,
#                reflow=False)
        self.emit("%s _HotPy_AST_%s(%s);" % (ctype, name, argstr), False)

    def visitProduct(self, prod, name):
        self.emit_function(name, get_c_type(name),
                           self.get_args(prod.fields), [], union=False)


class FunctionVisitor(PrototypeVisitor):
    """Visitor to generate constructor functions for AST."""

    def emit_function(self, name, ctype, args, attrs, union=True):
        def emit(s, depth=0, reflow=True):
            self.emit(s, depth, reflow)
        argstr = ", ".join(["%s %s" % (atype, aname)
                            for atype, aname, opt in args + attrs])
        self.emit("%s" % ctype, 0)
        emit("_HotPy_AST_%s(%s)" % (name, argstr))
        emit("{")
        emit("%s p;" % get_c_type(name), 1)
        #for argtype, argname, opt in args:
        #    if (not opt) and argtype != "int" and str(argname) != 'ctx':
        #        emit("if (!%s) {" % argname, 1)
        #        msg = "field %s is required for %s" % (argname, name)
        #        emit('raise_char(type_ValueError, "%s");' % msg,
        #             2, reflow=False)
        #        emit('}', 1)
        emit("p = gc_allocate(AST_%s);" % name, 1);
        emit("SET_TYPE(p, type_AST_%s);" % name, 1);
        emit("p->ref_count = 0;", 1)
        if union:
            self.emit_body_union(name, args, attrs)
        else:
            self.emit_body_struct(name, args, attrs)
        emit("gvmt_fully_initialized((GVMT_Object)p);", 1);
        emit("return (%s)p;" % ctype, 1)
        emit("}")
        emit("")

    def emit_body_union(self, name, args, attrs):
        def emit(s, depth=0, reflow=True):
            self.emit(s, depth, reflow)
        emit("p->visit_index = %s_VISIT_INDEX;" % str(name).upper(), 1)
        for argtype, argname, opt in args:
            emit("p->%s = %s;" % (argname, argname), 1)
        for argtype, argname, opt in attrs:
            emit("p->%s = %s;" % (argname, argname), 1)

    def emit_body_struct(self, name, args, attrs):
        def emit(s, depth=0, reflow=True):
            self.emit(s, depth, reflow)
        for argtype, argname, opt in args:
            emit("p->%s = %s;" % (argname, argname), 1)
        assert not attrs


class PickleVisitor(EmitVisitor):

    def visitModule(self, mod):
        for dfn in mod.dfns:
            self.visit(dfn)

    def visitType(self, type):
        self.visit(type.value, type.name)

    def visitSum(self, sum, name):
        pass

    def visitProduct(self, sum, name):
        pass

    def visitConstructor(self, cons, name):
        pass

    def visitField(self, sum):
        pass

class HotPyTypesVisitor(PickleVisitor):

    def visitModule(self, mod):
        self._emit_type('Visitor')
        for dfn in mod.dfns:
            self.visit(dfn)
    
    def _emit_type(self, name):
        ctype = get_c_type(name)
        self.emit("extern GVMT_OBJECT(type) _AST_%s;" % name, 0)
        self.emit("GVMT_OBJECT(type)* type_AST_%s = &_AST_%s;" % (name, name), 0)
        self.emit("", 0)

    def visitProduct(self, prod, name):
        self._emit_type(name)
        
    def visitSum(self, sum, name):
        self._emit_type(name)
        for t in sum.types:
            self.visitConstructor(t, name, is_simple(sum))

    def visitConstructor(self, cons, name, simple):
        ctype = get_c_type(name)
        self._emit_type(cons.name)
        if simple:
            self.emit("GVMT_OBJECT(AST_%s) hotpy_%s_singleton_object = {" % (cons.name, cons.name), 0)    
            self.emit("&_AST_%s," % cons.name, 1)  
            self.emit("IMMORTAL,", 1)
            self.emit("%s_VISIT_INDEX," % str(cons.name).upper(), 1)
            self.emit("};", 0)
            self.emit("%s hotpy_%s_singleton = (%s)&hotpy_%s_singleton_object;" % (ctype, cons.name, ctype, cons.name), 0)     
            self.emit("", 0)
        
class VisitorStructVisitor(PickleVisitor):

    def visitModule(self, mod):
        self.emit("GVMT_OBJECT(AST_Visitor) { // special ", 0)
        self.emit("GVMT_OBJECT(type)* ob_type;", 1)
        self.emit("uintptr_t ref_count;", 1)
        self.emit("intptr_t i;", 1)
        self.emit("void* p;", 1)
        for dfn in mod.dfns:
            self.visit(dfn)
        self.emit("};", 0)
        self.emit("GVMT_OBJECT(object)* r0;", 1)
        self.emit("GVMT_OBJECT(object)* r1;", 1)
        self.emit("GVMT_OBJECT(object)* r2;", 1)
        self.emit("GVMT_OBJECT(object)* r3;", 1)
    
    def visitSum(self, sum, name):
        l = len(sum.types)
        if l:
            self.emit("visit_%s_func %s_table[%d]; /*pointer*/" % (name, name, l), 1)
    
        
class VisitorPrototypeVisitor(PickleVisitor):
    "Visitor to generate prototypes and structs for visitors."

    def visitModule(self, mod):
        for dfn in mod.dfns:
            self.visit(dfn)
   
    def visitSum(self, sum, name):
        self.emit("typedef void (*visit_%s_func)(R_AST_%s object, R_AST_Visitor visitor);" % (name, name), 0)
        self.emit("void hotpy_visit_%s(R_AST_%s object, R_AST_Visitor visitor);" % (name, name), 0)
    
    def visitProduct(self, prod, name):
        self.emit("typedef void (*visit_%s_func)(R_AST_%s object, R_AST_Visitor visitor);" % (name, name), 0)
        self.emit("void hotpy_visit_%s(R_AST_%s object, R_AST_Visitor visitor);" % (name, name), 0)
    
class VisitorVisitor(PickleVisitor):
    "Visitor to generate visitor functions for AST."
 
    def visitSum(self, sum, name):
        self.emit_visitor(sum, name)
    
    def emit_visitor(self, sum, name):
        self.emit("void hotpy_visit_%s(R_AST_%s object, R_AST_Visitor visitor) {" % (name, name), 0)
        self.emit("if (object != NULL)", 1)
        self.emit("visitor->%s_table[object->visit_index](object, visitor);" % name, 2)
        self.emit("}", 0)
        self.emit("", 0)
   
   
class ConcretePrototypesVisitor(PickleVisitor):
    "Visitor to generate function prototypes for concrete visitor object."
    
    def __init__(self, f, name):
        PickleVisitor.__init__(self, f)
        self.name = name

    def visitModule(self, mod):
        for dfn in mod.dfns:
            self.visit(dfn)
        self.emit("R_AST_Visitor hotpy_make_%s_visitor(void);" % self.name, 0)
         
    def visitSum(self, sum, name):
        for t in sum.types:
            self.emit("void %s_visit_%s(R_AST_%s object, R_AST_Visitor visitor);" % (self.name, t.name, t.name), 0)
  
   
class ConcreteVisitorVisitor(PickleVisitor):
    "Visitor to generate concrete visitor object."
    
    def __init__(self, f, name):
        PickleVisitor.__init__(self, f)
        self.name = name

    def visitModule(self, mod):
        self.emit("R_AST_Visitor hotpy_make_%s_visitor(void) {" % self.name, 0)
        self.emit("R_AST_Visitor visitor = gc_allocate(AST_Visitor);", 1)
        self.emit("SET_TYPE(visitor, type_AST_Visitor);", 1)
        for dfn in mod.dfns:
            self.visit(dfn)
        self.emit("return visitor;", 1)
        self.emit("}", 0)

    def visitSum(self, sum, name):
        l = len(sum.types)
        if l:
            self.emit("visit_%s_func %s_table[%d]; /*pointer*/" % (name, name, l), 1)
        
    def visitSum(self, sum, name):
        for i, t in enumerate(sum.types):
            self.emit("visitor->%s_table[%d] = (visit_%s_func)%s_visit_%s;" % 
                         (name, i, name, self.name, t.name), 1)

def _print_func(t, seq):
    s = str(t)
    if s == 'object':
        p = '_hotpy_print_number'
    elif s == 'int':
        p = '_hotpy_print_int'
    elif s in [ 'string',  'identifier']:
        p = '_hotpy_print_string'
    elif seq:
        p = '_hotpy_print_%s' % s
    else:
        p = 'hotpy_visit_' + s
    if seq:
        p += '_list'
    return p    
    
class TemplateVisitor(PickleVisitor):
    """Template code for visitors"""
    
    def visitModule(self, mod):
        self.emit('/*', 0)
        for dfn in mod.dfns:
            self.visit(dfn)
        self.emit('*/', 0) 
        

    def _emit_list(self, name):
        ctype = get_c_type(name)
        func = _print_func(name, False)
        self.emit("static void template_visit_%s_list(R_list list, R_AST_Visitor visitor) {" % name, 0)
        self.emit("int i, len;", 1)
        self.emit("%s object;" % ctype, 1)
        self.emit("if (list == NULL) {", 1)
        self.emit('return;', 2)
        self.emit('}', 1)
        self.emit("len = LIST_SIZE(list);", 1)
        self.emit("for (i = 0; i < len; i++) {", 1)
        self.emit("object = (%s)ITEM(list->array, i);" % ctype, 2)
        self.emit("template_visit_%s(object, visitor);" % name, 2)
        self.emit("}", 1)
        self.emit("}", 0)
        self.emit("", 0)
    

    def _emit_visitor(self, name, fields, ctype):
        def emit(s, depth=0, reflow=True):
            self.emit(s, depth, reflow)
        func = 'template_visit_%s' % name
        emit("void %s(R_AST_%s object, R_AST_Visitor visitor) {" % (func, name))
        emit("FILE* out = (FILE*)visitor->p;", 1)
        emit("intptr_t indent = visitor->i;", 1)
        emit("if (object == NULL) {", 1)
        emit('fprintf(out, "NULL\\n");', 2)
        emit('return;', 2)
        emit('}', 1)
        emit("TYPE_ASSERT(object, AST_%s);" % name, 1)
        if fields:
            for f in fields:
                aname = f.name
                if aname is None:
                    aname = f.type
                optional = f.opt and str(f.type) != 'int'
                if optional:
                    emit("if (object->%s != NULL) " % aname, 1) 
                if f.seq:
                    func = 'template_visit_%s_list' % f.type
                else:
                    func = 'template_visit_%s' % f.type
                emit("%s(object->%s, visitor);" % (func, aname), optional+1)
        else:
            emit('template_do_%s();' % name, 1)
        emit("}")
        emit("")
        
    def visitSum(self, sum, name):
        for t in sum.types:
            self.visit(t, name, sum.attributes)
        self._emit_list(name)
           
    def visitProduct(self, prod, name):
        ctype = get_c_type(name)
        self._emit_visitor(name, prod.fields, ctype)
        self._emit_list(name)
                    
    def visitConstructor(self, cons, type, attrs):
        name = cons.name
        ctype = get_c_type(type)
        self._emit_visitor(name, cons.fields, ctype)
        
class PrintVisitor(PickleVisitor):
    """Visitor to generate print functions for print AST_Visitor."""
    
    def visitModule(self, mod):
        self.emit_support()
        self.emit_list('string')
        for dfn in mod.dfns:
            self.visit(dfn)
    
    def emit_support(self):
        self.emit('extern void _hotpy_print_number(R_object o, R_AST_Visitor visitor);', 0)
        self.emit('extern void _hotpy_print_string(R_str s, R_AST_Visitor visitor);', 0)
        self.emit('extern void _hotpy_print_int(int i, R_AST_Visitor visitor);', 0)
        self.emit('', 0)

    def emit_list(self, name):
        ctype = get_c_type(name)
        func = _print_func(name, False)
        self.emit("static void %s(R_list list, R_AST_Visitor visitor) {" % _print_func(name, True), 0)
        self.emit("FILE* out = (FILE*)visitor->p;", 1)
        self.emit("intptr_t indent = visitor->i;", 1)
        self.emit("int i, len;", 1)
        self.emit("%s object;" % ctype, 1)
        self.emit("if (list == NULL) {", 1)
        self.emit('fprintf(out, "NULL\\n");', 2)
        self.emit('return;', 2)
        self.emit('}', 1)
        self.emit("len = LIST_SIZE(list);", 1)
        self.emit('if (len == 0) {', 1)
        self.emit('fprintf(out, "[]\\n");', 2)
        self.emit("} else {", 1)
        self.emit('fprintf(out, "[\\n");', 2)
        self.emit("for (i = 0; i < len; i++) {", 2)
        self.emit("object = (%s)ITEM(list->array, i);" % ctype, 3)
        self.emit("_hotpy_print_spaces(out, indent+1);", 3)
        self.emit("%s(object, visitor);" % func, 3)
        self.emit("}", 2)
        self.emit("_hotpy_print_spaces(out, indent);", 2)
        self.emit('fprintf(out, "]\\n");', 2)
        self.emit("}", 1)
        self.emit("}", 0)
        self.emit("", 0)

    def _emit_printer(self, name, fields, ctype, cons):
        def emit(s, depth=0, reflow=True):
            self.emit(s, depth, reflow)
        if cons:
            func = 'print_visit_%s' % name
        else:
            func = _print_func(name, False)
        emit("void %s(R_AST_%s object, R_AST_Visitor visitor) {" % (func, name))
        emit("FILE* out = (FILE*)visitor->p;", 1)
        emit("intptr_t indent = visitor->i;", 1)
        emit("if (object == NULL) {", 1)
        emit('fprintf(out, "NULL\\n");', 2)
        emit('return;', 2)
        emit('}', 1)
        emit("TYPE_ASSERT(object, AST_%s);" % name, 1)
        emit("_hotpy_print_spaces(out, indent+1);", 1)
        if fields:
            emit('fprintf(out, "%s:\\n");' % name, 1)
            emit("visitor->i = indent+1;", 1)
            for f in fields:
                aname = f.name
                if aname is None:
                    aname = f.type
                emit("_hotpy_print_spaces(out, indent+1);", 1)
                emit('fprintf(out, "%%s = ", "%s");' % aname, 1)
                optional = f.opt and str(f.type) != 'int'
                if optional:
                    emit("if (object->%s != NULL) " % aname, 1) 
                func = _print_func(f.type, f.seq)
                emit("%s(object->%s, visitor);" % (func, aname), optional+1)
                if optional:
                    emit("else", 1)
                    if str(f.type) != 'int':
                        emit('fprintf(out, "NULL\\n");', 2)
                    else:
                        emit('fprintf(out, "0\\n");', 2)
            emit("visitor->i = indent;", 1)
        else:
            emit('fprintf(out, "%s.\\n");' % name, 1)
        emit("}")
        emit("")
        
    def visitSum(self, sum, name):
        for t in sum.types:
            self.visit(t, name, sum.attributes)
        #self.emit_visitor(sum, name)
        self.emit_list(name)
           
    def visitProduct(self, prod, name):
        ctype = get_c_type(name)
        self._emit_printer(name, prod.fields, ctype, False)
        self.emit_list(name)
                    
    def visitConstructor(self, cons, type, attrs):
        name = cons.name
        ctype = get_c_type(type)
        self._emit_printer(name, cons.fields, ctype, True)
    
            
class MarshalPrototypeVisitor(PickleVisitor):

    def prototype(self, sum, name):
        ctype = get_c_type(name)
        self.emit("static int marshal_write_%s(PyObject **, int *, %s);"
                  % (name, ctype), 0)

    visitProduct = visitSum = prototype
    
class PrintListPrototypeVisitor(PickleVisitor):
    
    def _proto(self, name):
        func = _print_func(name, True)
        self.emit("static void %s(R_list list, R_AST_Visitor visitor);" % func, 0)

    def visitModule(self, mod):
        self._proto('string')
        for dfn in mod.dfns:
            self.visit(dfn)
    
    def visitSum(self, sum, name):
        self._proto(name)

    def visitProduct(self, prod, name):
        self._proto(name)
    
class PrintPrototypeVisitor(PickleVisitor):

    def visitModule(self, mod):
        self.emit('extern void _hotpy_print_spaces(FILE* out, int times);', 0)
        self.emit('', 0)
        for dfn in mod.dfns:
            self.visit(dfn)        
        
#    def visitSum(self, sum, name):
#        func = _print_func(name, False)
#        self.emit("void %s(R_AST_%s object, FILE* out, int indent);" % (func, name), 0)
#
#    def visitProduct(self, prod, name):
#        func = _print_func(name, False)
#        self.emit("void %s(R_AST_%s object, FILE* out, int indent);" % (func, name), 0)

def parse_version(mod):
    return mod.version.value[12:-3]

class PyClassVisitor(PickleVisitor):

    def visitModule(self, mod):
        self.cls_decl('Visitor', 'object')
        for dfn in mod.dfns:
            self.visit(dfn)

    def visitProduct(self, prod, name):
        self.cls_decl(name, 'object')

    def visitSum(self, sum, name):
        self.cls_decl(name, 'object')
        for t in sum.types:
            self.visitConstructor(t, name)

    def visitConstructor(self, cons, name):
        self.cls_decl(cons.name, name)

    def cls_decl(self, name, super):
        self.emit('class %s(%s): pass' % (name, super), 0)


_SPECIALIZED_SEQUENCES = ('stmt', 'expr')

def find_sequence(fields, doing_specialization):
    """Return True if any field uses a sequence."""
    for f in fields:
        if f.seq:
            if not doing_specialization:
                return True
            if str(f.type) not in _SPECIALIZED_SEQUENCES:
                return True
    return False

def has_sequence(types, doing_specialization):
    for t in types:
        if find_sequence(t.fields, doing_specialization):
            return True
    return False


class StaticVisitor(PickleVisitor):
    CODE = '''Very simple, always emit this static code.  Overide CODE'''

    def visit(self, object):
        self.emit(self.CODE, 0, reflow=False)



class PartingShots(StaticVisitor):

    CODE = ""

class ChainOfVisitors:
    def __init__(self, *visitors):
        self.visitors = visitors

    def visit(self, object):
        for v in self.visitors:
            v.visit(object)
            v.emit("", 0)

common_msg = "/* File automatically generated by %s. */\n\n"

c_file_msg = """
/*
   __version__ %s.

   This module must be committed separately after each AST grammar change;
   The __version__ number is set to the revision number of the commit
   containing the grammar change.
*/

"""

def main(srcfile):
    argv0 = sys.argv[0]
    components = argv0.split(os.sep)
    argv0 = os.sep.join(components[-2:])
    auto_gen_msg = common_msg % argv0
    mod = asdl.parse(srcfile)
    if not asdl.check(mod):
        sys.exit(1)
    if INC_DIR:
        p = "%s/%s-ast.h" % (INC_DIR, mod.name)
        f = open(p, "w")
        f.write(auto_gen_msg)
        f.write('#ifndef %s_AST_H\n' % str(mod.name).upper())
        f.write('#define %s_AST_H\n' % str(mod.name).upper())
        c = ChainOfVisitors(TypeDefVisitor(f),
                            StructVisitor(f),
                            PrototypeVisitor(f),
                            PrintPrototypeVisitor(f),
                            VisitorPrototypeVisitor(f),
                            VisitorStructVisitor(f),
                            ConcretePrototypesVisitor(f, "print"),
                            ConcretePrototypesVisitor(f, "symbol"),
                            ConcretePrototypesVisitor(f, "codegen"),
                            )
        c.visit(mod)
        f.write('#endif\n')
        f.close()

    if SRC_DIR:
        p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c")
        f = open(p, "w")
        f.write(auto_gen_msg)
        f.write(c_file_msg % parse_version(mod))
        f.write('#include "hotpy.h"\n')
        f.write('#include "%s-ast.h"\n' % mod.name)
        f.write('\n')
        v = ChainOfVisitors(
            HotPyTypesVisitor(f),
            FunctionVisitor(f),
            PrintListPrototypeVisitor(f),
            VisitorVisitor(f),
            PrintVisitor(f),
            ConcreteVisitorVisitor(f, "print"),
            ConcreteVisitorVisitor(f, "symbol"),
            ConcreteVisitorVisitor(f, "codegen"),
            PartingShots(f),
            TemplateVisitor(f),
            )
        v.visit(mod)
        f.close()
    if PY_DIR:
        p = os.path.join(PY_DIR, "ast.py")
        f = open(p, "w")
        f.write('#' + auto_gen_msg)
        f.write('\n')
        v = ChainOfVisitors(
            PyClassVisitor(f),
            )
        v.visit(mod)
        f.close()

if __name__ == "__main__":
    import sys
    import getopt

    INC_DIR = ''
    SRC_DIR = ''
    PY_DIR = ''
    opts, args = getopt.getopt(sys.argv[1:], "h:c:p:")
    if len(opts) != 1:
        sys.stdout.write("Must specify exactly one output file\n")
        sys.exit(1)
    for o, v in opts:
        if o == '-h':
            INC_DIR = v
        if o == '-c':
            SRC_DIR = v
        if o == '-p':
            PY_DIR = v
    if len(args) != 1:
        sys.stdout.write("Must specify single input file\n")
        sys.exit(1)
    main(args[0])
